package edu.upc.fib.lamsandroid.client.activity;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.UncachedSpiceService;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import edu.upc.fib.lamsandroid.client.LamsAndroidClientApplication;
import edu.upc.fib.lamsandroid.client.R;
import edu.upc.fib.lamsandroid.client.adapters.SequenceListAdapter;
import edu.upc.fib.lamsandroid.client.dialog.MessageBoxDialog;
import edu.upc.fib.lamsandroid.client.fragment.lesson.*;
import edu.upc.fib.lamsandroid.client.request.activity.GetActivityByIdRequest;
import edu.upc.fib.lamsandroid.client.request.lesson.GetLessonByIdRequest;
import edu.upc.fib.lamsandroid.server.api.model.Lesson;
import edu.upc.fib.lamsandroid.server.api.model.ToolType;
import edu.upc.fib.lamsandroid.server.api.response.Response;
import edu.upc.fib.lamsandroid.server.api.response.lesson.GetByIdResponse;

public class LessonActivity extends AbstractBaseActivity implements AdapterView.OnItemClickListener {
    private SpiceManager spiceManager = new SpiceManager(UncachedSpiceService.class);

    private SequenceListAdapter sequenceListAdapter;

    private Lesson currentLesson;

    @Override
    public void onStart() {
        spiceManager.start(getApplicationContext());
        super.onStart();
    }

    @Override
    public void onStop() {
        spiceManager.shouldStop();
        super.onStop();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.lesson);

        fetchLesson();
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        sequenceListAdapter.setSelectedIndex(position);
        view.setSelected(true);
        fetchActivity(position);
    }

    private void fetchLesson() {
        setProgressBarIndeterminateVisibility(true);

        Long lessonId = LamsAndroidClientApplication.getInstance().getCurrentLesson().getExternalId();

        GetLessonByIdRequest getByIdRequest = new GetLessonByIdRequest(lessonId);
        spiceManager.execute(getByIdRequest, new RequestListener<GetByIdResponse>() {
            @Override
            public void onRequestFailure(SpiceException e) {
                setProgressBarIndeterminateVisibility(false);
                new MessageBoxDialog(LessonActivity.this).show(e.toString());
            }

            @Override
            public void onRequestSuccess(GetByIdResponse getByIdResponse) {
                setProgressBarIndeterminateVisibility(false);

                switch(getByIdResponse.getCode()) {
                    case Response.OPERATION_SUCCESSFUL:
                        currentLesson = getByIdResponse.getPayload().get(0);
                        renderSequence();
                        break;
                    default:
                        new MessageBoxDialog(LessonActivity.this).show("Error, code: " + getByIdResponse.getCode());
                        break;
                }
            }
        });
    }

    private void renderSequence() {
        ListView listView = (ListView) findViewById(R.id.sequence);
        sequenceListAdapter = new SequenceListAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,
                currentLesson.getActivities());

        listView.setAdapter(sequenceListAdapter);
        listView.setOnItemClickListener(this);

        sequenceListAdapter.notifyDataSetChanged();
    }

    private void fetchActivity(int index) {
        setProgressBarIndeterminateVisibility(true);

        GetActivityByIdRequest request = new GetActivityByIdRequest(currentLesson.getActivities().get(index).getExternalId());
        spiceManager.execute(request, new RequestListener<edu.upc.fib.lamsandroid.server.api.response.activity.GetByIdResponse>() {
            @Override
            public void onRequestFailure(SpiceException e) {
                setProgressBarIndeterminateVisibility(false);
                new MessageBoxDialog(LessonActivity.this).show(e.toString());
            }

            @Override
            public void onRequestSuccess(edu.upc.fib.lamsandroid.server.api.response.activity.GetByIdResponse getByIdResponse) {
                setProgressBarIndeterminateVisibility(false);

                switch(getByIdResponse.getCode()) {
                    case Response.OPERATION_SUCCESSFUL:
                        edu.upc.fib.lamsandroid.server.api.model.Activity activity = getByIdResponse.getPayload().get(0);
                        renderActivity(activity);
                        break;
                    default:
                        new MessageBoxDialog(LessonActivity.this).show("Error, code: " + getByIdResponse.getCode());
                        break;
                }
            }
        });

    }

    private void renderActivity(edu.upc.fib.lamsandroid.server.api.model.Activity activity) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();

        Fragment lessonFragment;

        switch(activity.getToolType().getExternalId().intValue()) {
            case ToolType.NOTICEBOARDX: lessonFragment = new NoticeBoardLessonFragment(activity.getToolContent()); break;
            case ToolType.IMAGE_GALLERY: lessonFragment = new ImageGalleryLessonFragment(activity.getToolContent()); break;
            case ToolType.SHARED_RESOURCES: lessonFragment = new SharedResourcesLessonFragment(activity.getToolContent()); break;
            case ToolType.ASSESSMENT: lessonFragment = new AssessmentLessonFragment(activity.getToolContent()); break;

            case ToolType.FORUM:
            case ToolType.QUESTION_AND_ANSWER:
            case ToolType.SUBMIT_FILE:
            case ToolType.CHAT:
            case ToolType.VOTING:
            case ToolType.NOTEBOOK:
            case ToolType.SURVEY:
            case ToolType.SCRIBE:
            case ToolType.SHARED_TASKLIST:
            case ToolType.GMAP:
            case ToolType.SPREADSHEET:
            case ToolType.DATA_COLLECTION:
            case ToolType.WIKI:
            case ToolType.VIDEO_RECORDER:
            case ToolType.MINDMAP:
            case ToolType.PIXLR:
            case ToolType.EADVENTURE:
            case ToolType.WOOKIE:
            case ToolType.SHARED_COMMON_CARTRIDGE:
            case ToolType.BBB:
            case ToolType.MCQ:
            case ToolType.DIMDIM:
            default:
                lessonFragment = new PlaceHolderLessonFragment(activity.getToolType()); break;
        }

        ft.replace(R.id.the_frag, lessonFragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.addToBackStack(null);

        ft.commit();
    }
}